<?php

namespace App\Console\Commands\Fee;

use App\Models\Fee\FeeAnnualOrderModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Remote\Rms\RmsMqttRemote;
use App\Remote\Rms\RmsUserRemote;
use App\Service\System\SystemNotifyService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;

class PushAnnualFeeOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fee:push-annual-fee-order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '推送每年的年费订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        //推送规则
        // 1. 90天推送一次  2. 60天推送一次   3.  从30天起 每天推送
        //数据堆积
        $shopIds  = [];
        $pushData = [];
        FeeAnnualOrderModel::query()
            ->whereIn('payStatus', [FeeAnnualOrderModel::PAY_STATUS_WAIT, FeeAnnualOrderModel::PAY_STATUS_PART])
            ->orderBy('endTime')
            ->get()
            ->each(function ($item) use (&$pushData, &$shopIds) {

                //获得过期时间 $item->endTime
                $thisStartTime = strtotime(date('Y-m-d', $item->endTime) . ' 00:00:00');
                $thisEndTime   = strtotime(date('Y-m-d', $item->endTime) . ' 23:59:59');

                //前90天满足
                $ninetyStart = strtotime('-90day', $thisStartTime);
                $ninetyEnd   = strtotime('-90day', $thisEndTime);

                //前60天满足
                $sixtyStart = strtotime('-60day', $thisStartTime);
                $sixtyEnd   = strtotime('-60day', $thisEndTime);

                //前30天的时间
                $thirtyStart = strtotime('-30day', $thisStartTime);
                $thirtyEnd   = strtotime('-30day', $thisEndTime);

                //前29天的时间
                //$twentyNineStart = strtotime('-29day', $thisStartTime);
                //$twentyNineEnd   = strtotime('-29day', $thisEndTime);

                //修改为三天内
                $threeStart = strtotime('-3day', $thisStartTime);
                $threeEnd   = strtotime('-3day', $thisEndTime);

                $day             = (int)(($item->endTime - strtotime(date('Y-m-d') . ' 00:00:00')) / 86400);

                if (time() > $thisStartTime && time() <= $thisEndTime) {
                    $noticeList = self::noticeList($item->feeOrderNo, $item->shopId, '您的年费订单今天即将过期，请尽快完成支付，感谢你的理解！');
                    RmsMqttRemote::sendMqtt($item->shopId, RmsMqttRemote::MQTT_COMMAND_FEE_ORDER, ['day' => $day]);
                    $shopIds[]  = $noticeList['shopId'];
                    $pushData[] = $noticeList['pushData'];
                } elseif (time() > $threeStart && time() <= $thisEndTime) {
                    $noticeList = self::noticeList($item->feeOrderNo, $item->shopId, '您的年费订单即将过期，请尽快完成支付，感谢你的理解！');
                    RmsMqttRemote::sendMqtt($item->shopId, RmsMqttRemote::MQTT_COMMAND_FEE_ORDER, ['day' => $day]);
                    $shopIds[]  = $noticeList['shopId'];
                    $pushData[] = $noticeList['pushData'];
                } elseif (time() > $thirtyStart && time() <= $thirtyEnd) {
                    $noticeList = self::noticeList($item->feeOrderNo, $item->shopId, '您的年费订单已生成，请注意查收！');
                    RmsMqttRemote::sendMqtt($item->shopId, RmsMqttRemote::MQTT_COMMAND_FEE_ORDER, ['day' => $day]);
                    $shopIds[]  = $noticeList['shopId'];
                    $pushData[] = $noticeList['pushData'];
                } elseif (time() > $sixtyStart && time() < $sixtyEnd) {
                    $noticeList = self::noticeList($item->feeOrderNo, $item->shopId, '您的年费订单已生成，请注意查收！');
                    RmsMqttRemote::sendMqtt($item->shopId, RmsMqttRemote::MQTT_COMMAND_FEE_ORDER, ['day' => $day]);
                    $shopIds[]  = $noticeList['shopId'];
                    $pushData[] = $noticeList['pushData'];
                } elseif (time() > $ninetyStart && time() < $ninetyEnd) {
                    $noticeList = self::noticeList($item->feeOrderNo, $item->shopId, '您的年费订单已生成，请注意查收！');
                    RmsMqttRemote::sendMqtt($item->shopId, RmsMqttRemote::MQTT_COMMAND_FEE_ORDER, ['day' => $day]);
                    $shopIds[]  = $noticeList['shopId'];
                    $pushData[] = $noticeList['pushData'];
                }
            });
        //只会发送一次消息
        $noticeIds      = array_values(array_column($pushData, 'id', 'shopId'));
        $manageShopList = array_values(array_column((RmsUserRemote::getShopManagerUserByShopId($shopIds)['lists'] ?? []), null, 'userId'));
        Config::set('event.connection', 'sync');
        //权重控制
        foreach ($manageShopList as $value) {
            foreach ($pushData as $datum) {
                if ($value['shopId'] == $datum['shopId']) {
                    dump('已给店长（' . $value['username'] . '）推送年费订单');
                    SystemNotifyService::preSend($datum['id'], [$value['userId']]);
                    break;
                }
            }
        }
        //删除所有消息  暂不删除  列表做控制  【删除会影响消息中心数据统计】
        //SystemNotifyCenterModel::query()->whereIn('id', $noticeIds)->delete();
    }

    public static function noticeList($feeOrderNo, $shopId, $content): array
    {
        $notify = SystemNotifyService::save(
            false,
            '管理费到期通知',
            SystemNotifyCenterModel::NOTIFY_TYPE_3,
            SystemNotifyCenterModel::NOTIFY_TARGET_1,
            '',
            '管理费到期通知',
            sprintf(config('feeOrder.' . (config('app.env') . 'Url')), $feeOrderNo, $shopId, time()),
            SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
            $content,
            '',
            SystemNotifyCenterModel::IS_POPUP_OFF,
            '1'
        );
        SystemNotifyService::recordLog($notify, '创建消息');
        return [
            'shopId'   => $shopId,
            'pushData' => [
                'id'     => $notify->id,
                'shopId' => $shopId
            ]
        ];
    }

}
